/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.thinkcube.edutainment.login;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.social.connect.DuplicateConnectionException;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.thinkcube.edutainment.EdutainmentConstant;
import com.thinkcube.edutainment.SplashActivity_;

/**
 * This class is based on the FacebookWebOAuthActivity by Roy Clarkson
 */
@EActivity
public class DialogWebOAuthActivity extends AbstractWebViewActivity {

	private static final String TAG = DialogWebOAuthActivity.class
			.getSimpleName();

	// ***************************************
	// Activity methods
	// ***************************************
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// javascript is mandatory
		getWebView().getSettings().setJavaScriptEnabled(true);

		// Using a custom web view client to capture the access token
		getWebView().setWebViewClient(new DialogOAuthWebViewClient());

	}

	@Override
	public void onStart() {
		super.onStart();

		// display the Google authorization page
		getWebView().loadUrl(getAuthorizeUrl());
	}

	// ***************************************
	// Private methods
	// ***************************************
	private String getAuthorizeUrl() {
		String redirectUri = EdutainmentConstant.DIALOG_OAUTH_CALLBACK_URL;

		return redirectUri;
	}

	private void displayGoogleOptions() {
		Intent intent = new Intent();
		intent.setClass(this, SplashActivity_.class);
		startActivity(intent);
		finish();
	}

	// ***************************************
	// Private classes
	// ***************************************
	private class DialogOAuthWebViewClient extends WebViewClient {

		private static final String LOCALHOST = "/login-response";
		private static final String CODE = "code";

		/*
		 * The WebViewClient has another method called shouldOverridUrlLoading
		 * which does not capture the javascript redirect to the success page.
		 * So we're using onPageStarted to capture the url.
		 */
		@Override
		public void onPageStarted(final WebView view, final String url,
				final Bitmap favicon) {
			// parse the captured url
			Uri uri = Uri.parse(url);
			// log the url : very interesting for debugging the OAuth workflow
			Log.d(TAG, url);

			// /*
			// * The WebViewClient is launched to load an URL from the provider
			// * that will ask the user whether or not he accepts our app to
			// * access his data. Once the provider successfully gets the
			// approval
			// * from the user, it will redirect this WebViewClient to the
			// * callback_uri, with a query parameter named "code" : this is the
			// * authorization code
			// */
			String host = uri.getHost();
			// String code = uri.getQueryParameter;
			System.out.println("onPageStarted  " + host);
			//
			// // The WebViewClient is redirected to the callback_uri, let's
			// trade
			// // the authorization code for the access token
			// if (LOCALHOST.equals(host)) {
			// System.out.println("test");
			// getHtml(url);
			//
			// }
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			boolean shouldOverride = false;
			Uri uri = Uri.parse(url);
			System.out.println("eve befo " + uri.getHost());
			System.out.println("eve getPath " + uri.getPath());

			if (LOCALHOST.equals(uri.getPath())) { // NON-NLS
				// DO SOMETHING
				System.out.println("eve " + uri.getEncodedPath());
				getHtml(url);
				// finish();
				shouldOverride = true;
			}
			return shouldOverride;
		}
	}

	@Background
	void getHtml(String url) {
		HttpClient vClient = new DefaultHttpClient();
		HttpGet vGet = new HttpGet(url);
		String response = "";

		try {
			ResponseHandler<String> vHandler = new BasicResponseHandler();
			response = vClient.execute(vGet, vHandler);
			System.out.println(response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private final AsyncTask<String, Void, Void> exchangeAuthorizationCodeForAccessToken = new AsyncTask<String, Void, Void>() {

		private Exception exception;

		@Override
		protected Void doInBackground(final String... params) {
			// executed by a background thread
			// params[0] should contain the authorization code
			try {

				Log.d(TAG, "AccessToken  : " + params[0]);

			} catch (DuplicateConnectionException e) {
				Log.e(TAG,
						"something went wrong when adding the accessToken to the connection repository",
						e);
				exception = e;
			} catch (Exception e) {
				Log.e(TAG,
						"something went wrong when adding the accessToken to the connection repository",
						e);
				exception = e;
			}
			return null;
		}

		@Override
		protected void onPostExecute(final Void result) {
			// executed by the UI thread once the background thread is done
			// getting the result
			if (exception != null) {
				Toast.makeText(getApplicationContext(), exception.getMessage(),
						Toast.LENGTH_LONG).show();
			}
			// we go back to the main activity to display the options
			displayGoogleOptions();
		}

	};

}
